// 七牛云云托管存储

const express = require('express')
const qiniuStorage = express.Router();
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const formidable = require("formidable");
const { verifyToken } = require('../utils/verifyToken');
// 引入七牛模块
var qiniu = require("qiniu");

var scope = "my-circle1";//要上传的空间名
var imageUrl = "http://s7hpk87ue.hn-bkt.clouddn.com/"; // 域名名称
var accessKey = "IcRXxZJDuJ_eTma4mQlCqqs99_dJAmJrJa_gdM0H";
var secretKey = "gu_6Xqfu_0Jpvo_G3_VVg354HxoWf1_uEsb2PbDa";


var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var options = { scope };
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);

var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z2;


// 前端参数字段 file
qiniuStorage.post("/upload", multer({
    //设置文件存储路径
    dest: "./public/image/",
}).array("file", 1), async (req, res) => {
    // 文件路径
    const { token } = req.body
   
    try {
        const vToken = await verifyToken(token)
        if (!!vToken) {

            var filePath = "./" + req.files[0].path;
            // console.log(filePath, "filePath");
            // 文件类型
            var temp = req.files[0].originalname.split(".");
            // console.log(temp, "temp");

            var fileType = temp[temp.length - 1];
            // console.log(fileType, "fileType");

            var lastName = "." + fileType;
            // console.log(lastName, "lastName");

            // 构建图片名
            var fileName = Date.now() + lastName;
            // console.log(fileName, "fileName");

            var formUploader = new qiniu.form_up.FormUploader(config);
            var putExtra = new qiniu.form_up.PutExtra();
            // console.log(uploadToken, "uploadToken");

            // 图片重命名
            fs.rename(filePath, "./public/image/" + fileName, async (err) => {
                if (err) {
                    return "";
                } else {
                    var localFile = "./public/image/" + fileName;
                    var key = fileName;
                    try {
                        // 文件上传 
                        formUploader.putFile(
                            uploadToken,
                            key,
                            localFile,
                            putExtra,
                            (respErr, respBody, respInfo) => {
                                if (respErr) {
                                    return res.send(respErr);
                                }
                                if (respInfo.statusCode == 200) {
                                    var imageSrc = imageUrl + respBody.key;
                                    res.send({
                                        statusCode: 200,
                                        msg: "上传成功",
                                        imageUrl: imageSrc,
                                    });
                                } else {
                                    return res.send(respBody);
                                }

                                // 上传之后删除本地文件
                                fs.unlinkSync(localFile);
                            }
                        );
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        }
    } catch (err) {
        res.send({
            code: 401,
            msg: "验证失败，token 无效或过期"
        });
    }

});



module.exports = qiniuStorage;